import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../core/constants/app_constants.dart';
import '../../core/constants/emotion_constants.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';

/// 快速记录组件
/// Quick record widget for fast emotion recording
class QuickRecordWidget extends StatefulWidget {
  /// 快速记录回调
  /// Quick record callback
  final Function(String emotionType)? onQuickRecord;

  /// 是否启用
  /// Whether enabled
  final bool enabled;

  /// 显示的情绪类型列表
  /// List of emotion types to display
  final List<String>? emotionTypes;

  const QuickRecordWidget({
    super.key,
    this.onQuickRecord,
    this.enabled = true,
    this.emotionTypes,
  });

  @override
  State<QuickRecordWidget> createState() => _QuickRecordWidgetState();
}

class _QuickRecordWidgetState extends State<QuickRecordWidget>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late List<AnimationController> _itemControllers;
  late List<Animation<double>> _scaleAnimations;
  late List<Animation<Offset>> _slideAnimations;

  // 默认显示的快速记录情绪类型
  // Default quick record emotion types
  static const List<String> _defaultEmotionTypes = [
    'happy',
    'sad',
    'angry',
    'anxious',
    'excited',
    'calm',
  ];

  List<String> get _emotionTypes => widget.emotionTypes ?? _defaultEmotionTypes;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  @override
  void dispose() {
    _animationController.dispose();
    for (final controller in _itemControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  /// 初始化动画
  /// Initialize animations
  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    // 为每个情绪项创建动画控制器
    // Create animation controllers for each emotion item
    _itemControllers = List.generate(
      _emotionTypes.length,
      (index) => AnimationController(
        duration: const Duration(milliseconds: 200),
        vsync: this,
      ),
    );

    // 创建缩放动画
    // Create scale animations
    _scaleAnimations = _itemControllers.map((controller) {
      return Tween<double>(
        begin: 1.0,
        end: 0.9,
      ).animate(CurvedAnimation(
        parent: controller,
        curve: Curves.easeInOut,
      ));
    }).toList();

    // 创建滑入动画
    // Create slide animations
    _slideAnimations = List.generate(_emotionTypes.length, (index) {
      final startTime = (index * 0.1).clamp(0.0, 0.4);
      final endTime = (startTime + 0.6).clamp(startTime, 1.0);
      
      return Tween<Offset>(
        begin: Offset(0.5, 0),
        end: Offset.zero,
      ).animate(CurvedAnimation(
        parent: _animationController,
        curve: Interval(
          startTime,
          endTime,
          curve: Curves.easeOutCubic,
        ),
      ));
    });

    // 启动入场动画
    // Start entrance animation
    _animationController.forward();
  }

  /// 处理快速记录点击
  /// Handle quick record tap
  void _onQuickRecordTap(String emotionType, int index) {
    if (!widget.enabled) return;

    // 播放点击动画
    // Play tap animation
    _itemControllers[index].forward().then((_) {
      _itemControllers[index].reverse();
    });

    // 触发回调
    // Trigger callback
    widget.onQuickRecord?.call(emotionType);

    // 显示反馈
    // Show feedback
    _showFeedback(emotionType);
  }

  /// 显示反馈
  /// Show feedback
  void _showFeedback(String emotionType) {
    final label = EmotionConstants.getEmotionLabel(emotionType);
    final emoji = EmotionConstants.getEmotionEmoji(emotionType);

    Get.snackbar(
      '快速记录',
      '正在记录 $emoji $label 情绪...',
      duration: const Duration(seconds: 2),
      backgroundColor:
          EmotionConstants.getEmotionColor(emotionType).withOpacity(0.9),
      colorText: Colors.white,
      icon: Icon(
        Icons.flash_on,
        color: Colors.white,
      ),
      margin: const EdgeInsets.all(AppConstants.paddingMedium),
      borderRadius: AppConstants.radiusMedium,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 说明文字
        // Description text
        Text(
          '点击下方按钮快速记录常见情绪',
          style: AppTextStyles.bodyMedium.copyWith(
            color: AppColors.textSecondary,
          ),
        ),

        SizedBox(height: 16.h),

        // 快速记录按钮网格
        // Quick record button grid
        _buildQuickRecordGrid(),
      ],
    );
  }

  /// 构建快速记录网格
  /// Build quick record grid
  Widget _buildQuickRecordGrid() {
    return Wrap(
      spacing: 8.w,
      runSpacing: 8.h,
      children: _emotionTypes.asMap().entries.map((entry) {
        final index = entry.key;
        final emotionType = entry.value;

        return AnimatedBuilder(
          animation: _animationController,
          builder: (context, child) {
            return SlideTransition(
              position: _slideAnimations[index],
              child: FadeTransition(
                opacity: _animationController,
                child: _buildQuickRecordButton(emotionType, index),
              ),
            );
          },
        );
      }).toList(),
    );
  }

  /// 构建快速记录按钮
  /// Build quick record button
  Widget _buildQuickRecordButton(String emotionType, int index) {
    final color = EmotionConstants.getEmotionColor(emotionType);
    final label = EmotionConstants.getEmotionLabel(emotionType);
    final emoji = EmotionConstants.getEmotionEmoji(emotionType);
    final icon = EmotionConstants.getEmotionIcon(emotionType);

    return AnimatedBuilder(
      animation: _itemControllers[index],
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimations[index].value,
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: () => _onQuickRecordTap(emotionType, index),
              borderRadius: BorderRadius.circular(12.r),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                padding: EdgeInsets.symmetric(
                  horizontal: 16.w,
                  vertical: 8.h,
                ),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      color.withOpacity(0.1),
                      color.withOpacity(0.05),
                    ],
                  ),
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(
                    color: color.withOpacity(0.3),
                    width: 1.w,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: color.withOpacity(0.1),
                      blurRadius: 4.r,
                      offset: Offset(0, 2.h),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 表情符号或图标
                    // Emoji or icon
                    if (emoji.isNotEmpty)
                      Text(
                        emoji,
                        style: TextStyle(fontSize: 16.sp),
                      )
                    else
                      Icon(
                        icon,
                        size: 16.sp,
                        color: color,
                      ),

                    SizedBox(width: 8.w),

                    // 标签
                    // Label
                    Text(
                      label,
                      style: AppTextStyles.bodyMedium.copyWith(
                        color: color,
                        fontWeight: FontWeight.w600,
                        fontSize: 14.sp,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

/// 快速记录按钮组件
/// Quick record button component
class QuickRecordButton extends StatelessWidget {
  /// 情绪类型
  /// Emotion type
  final String emotionType;

  /// 点击回调
  /// Tap callback
  final VoidCallback? onTap;

  /// 是否启用
  /// Whether enabled
  final bool enabled;

  /// 按钮大小
  /// Button size
  final Size? size;

  const QuickRecordButton({
    super.key,
    required this.emotionType,
    this.onTap,
    this.enabled = true,
    this.size,
  });

  @override
  Widget build(BuildContext context) {
    final color = EmotionConstants.getEmotionColor(emotionType);
    final label = EmotionConstants.getEmotionLabel(emotionType);
    final emoji = EmotionConstants.getEmotionEmoji(emotionType);
    final icon = EmotionConstants.getEmotionIcon(emotionType);

    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: enabled ? onTap : null,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        child: Container(
          width: size?.width,
          height: size?.height,
          padding: const EdgeInsets.all(AppConstants.paddingSmall),
          decoration: BoxDecoration(
            color: enabled ? color.withOpacity(0.1) : AppColors.surfaceLight,
            borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
            border: Border.all(
              color: enabled ? color.withOpacity(0.3) : AppColors.borderColor,
              width: 1,
            ),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 表情符号或图标
              // Emoji or icon
              if (emoji.isNotEmpty)
                Text(
                  emoji,
                  style: TextStyle(
                    fontSize: 20,
                    color: enabled ? null : AppColors.textDisabled,
                  ),
                )
              else
                Icon(
                  icon,
                  size: 20,
                  color: enabled ? color : AppColors.textDisabled,
                ),

              const SizedBox(height: 4),

              // 标签
              // Label
              Text(
                label,
                style: AppTextStyles.bodySmall.copyWith(
                  color: enabled ? color : AppColors.textDisabled,
                  fontWeight: FontWeight.w600,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
